package com.zzy.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.ServletContext;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component("csh")
public class Csh
{
    @Autowired
    ServletContext servletContext;
    public void chs() throws Exception {
        W1 w1 = new W1();
        //链接zookeeper
        ZooKeeper zooKeeper = new ZooKeeper("127.0.0.1:2181", 10000, w1);
        servletContext.setAttribute("zk",zooKeeper);
        w1.zk=zooKeeper;
        servletContext.setAttribute("w",w1);
        //查询子节点 开启触发监听器
        List<String> children = zooKeeper.getChildren("/server", true);
        if(children.size()==0 || children==null)
        {
            //目前没有开启的服务器,持续监听下去
        }
        else
        {   //有开启的服务器,先存一下,然后持续监听下去
            ArrayList<String> l = new ArrayList<>();
            for (String p: children) {
                byte[] data = zooKeeper.getData("/server/" + p, true, null);
                //从子节点取值获得url
                String url = new String(data);
                l.add(url);

            }
            ListUrl.list=l;
            System.out.println(ListUrl.list);
        }
    }
}
